package de.dopichaj.labrador.inex;


import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import de.dopichaj.labrador.inex.SubmissionWriter.Task;
import de.dopichaj.labrador.inex.assess.XCGAssessor;
import de.dopichaj.labrador.search.XMLSearchPostProcessor;
import de.dopichaj.labrador.search.hit.DocHitMap;
import de.dopichaj.labrador.search.hit.Hit;
import de.dopichaj.labrador.search.prune.NullPruner;
import de.dopichaj.labrador.search.prune.ResultTreePruner;
import de.dopichaj.labrador.util.LabradorVersion;


/**
 * A class for applying a list of postprocessors to retrieval results and
 * writing all intermediate results as submissions.
 */
public final class IncrementalPostProcessor {

    private static final Logger log = Logger.getLogger(HitListSorter.class);
    /**
     * The number of results to include in the submission.
     */
    private final int resultMax;
    /**
     * The year of the INEX workshop (determines submission file format).
     */
    private final int year;
    private final boolean useSubmissionWriter;
    
    private final Map<Integer, XCGAssessor> assessorMap;
    
    private final List<SavingPostProcessor> postProcessors =
        new ArrayList<SavingPostProcessor>();

    /**
     * 
     * @param year
     *      The year of the INEX workshop (determines submission file format).
     */
    public IncrementalPostProcessor(int year, int resultMax, boolean useSubmissionWriter,
        Map<Integer, XCGAssessor> assessorMap) {
        this.year = year;
        this.resultMax = resultMax;
        this.useSubmissionWriter = useSubmissionWriter;
        this.assessorMap = assessorMap;
    }
    
   private SubmissionWriter makeWriter(Writer writer, String type, Task task,
        String id, String description) {
        
        return new SubmissionWriter(year, writer, type, task,
            id, description + "\nsearch engine revision: " +
            LabradorVersion.getVersion() + "\n",
            task == Task.THOROUGH ? assessorMap : null);
    }
    
    public void addPostProcessor(ResultTreePruner pruner,
        Writer focusedw, String type, Task task, String id,
        String description) {
        
        addPostProcessor(pruner, focusedw, type, task, id, description,
            new HitListSorter() {

            private final Comparator<Hit> comparator =
                new LengthScoreComparator();
            public List<Hit> sort(List<Hit> hits) {
                Collections.sort(hits, comparator);
                return hits;
            }
        });
    }

    public void addPostProcessor(ResultTreePruner pruner, Writer writer,
        String type, Task task, String id, String description,
        HitListSorter sorter) {
        
        if (useSubmissionWriter) {
            final SubmissionWriter submissionWriter = makeWriter(writer, type,
                task, id, description + "\n" + pruner.getDescription());
            postProcessors.add(
                new SubmissionWriterSavingPostProcessor(pruner, submissionWriter,
                    sorter, resultMax));
        } else {
            postProcessors.add(new DocHitMapSavingPostProcessor(pruner, writer));
        }
    }
    
    public interface HitListSorter {
        /**
         * Sort the given list.
         */
        public List<Hit> sort(List<Hit> hits);
    }

    private interface SavingPostProcessor {
        public void pruneAndWrite(DocHitMap hitMap, int topicID);
        public void close();
    }
    
    private static final class DocHitMapSavingPostProcessor
        implements SavingPostProcessor {

        private final XMLSearchPostProcessor postProcessor;
        private final PrintWriter printWriter;
        
        public DocHitMapSavingPostProcessor(ResultTreePruner pruner, Writer writer) {
            
            this.postProcessor = new XMLSearchPostProcessor(pruner);
            this.printWriter = new PrintWriter(writer);
            printWriter.println("<?xml version='1.0'?>");
            printWriter.println("<resultset>");
        }

        public void pruneAndWrite(DocHitMap hitMap, int topicID) {
            
            log.info("... pruning");
            postProcessor.prune(hitMap);
            printWriter.println("<topic id='" + topicID + "'>");
            hitMap.writeResult(printWriter);
            printWriter.println("</topic>");
        }

        public void close() {
            printWriter.println("</resultset>");
            printWriter.close();
        }
    }
    
    private static final class SubmissionWriterSavingPostProcessor
        implements SavingPostProcessor {
        
        private final XMLSearchPostProcessor postProcessor;
        private final SubmissionWriter writer;
        private final HitListSorter sorter;
        private final int resultMax;
        
        public SubmissionWriterSavingPostProcessor(ResultTreePruner pruner,
            SubmissionWriter writer, HitListSorter sorter, int resultMax) {
            
            this.postProcessor = pruner instanceof NullPruner
                ? null
                : new XMLSearchPostProcessor(pruner);
            this.writer = writer;
            this.sorter = sorter;
            this.resultMax = resultMax;
        }

        public void pruneAndWrite(DocHitMap hitMap, int topicID) {
            
            log.info("... pruning " + hitMap.getHits().size());
            if (postProcessor != null) {
                postProcessor.prune(hitMap);
            }
            final List<Hit> hits = hitMap.getHits();
            log.info("... sorting");
            sorter.sort(hits);
            
            // keep only the wanted number of hits
            final List<Hit> newHits = hits.subList(0,
                Math.min(resultMax, hits.size()));

            log.info("... writing");
            writer.writeResultList(topicID, newHits);
        }
        
        public void close() {
            writer.close();
        }
    }

    public void close() {
        for (SavingPostProcessor pp : postProcessors) {
            pp.close();
        }
    }

    /**
     * Prune the given results and write them to the results with the given
     * topic ID.
     * Pruning and writing is done in the order the pruners were added.
     */
    public void pruneAndWrite(int topicID, DocHitMap results) {
        for (SavingPostProcessor pp : postProcessors) {
            pp.pruneAndWrite(results, topicID);
        }
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/